<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="app">
    <table border="1">
      <thead>
        <tr>
          <th>全选<input type="checkbox" v-model="checkAll" @change="selectAll"></th>
          <th>商品名称</th>
          <th>商品单价</th>
          <th>商品数量</th>
          <th>商品小计</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in goodsList">
          <td><input type="checkbox" v-model="item.checked" @change="selectItem(index)"></td>
          <td>{{item.name}}</td>
          <td>{{item.price}}</td>
          <td>{{item.num}}</td>
          <td>￥{{item.price * item.num}}元</td>
        </tr>
        <tr>
          <td></td>
          <td>总数量</td>
          <td>{{totalNum}}</td>
          <td>总金额</td>
          <td>{{totalPrice}}</td>
        </tr>
      </tbody>
    </table>
  </div>
  <script src="../vue.js"></script>
  <script>
    let vm = new Vue({
      el: '#app',
      data: {
        goodsList: [
          { name: 'iphone', num: 5, price: 5999 },
          { name: 'huawei', num: 15, price: 6999 },
          { name: 'xiaomi', num: 10, price: 5899 },
          { name: 'vivo', num: 12, price: 4599 },
        ],
        // 是否全选
        checkAll: false
      },
      created() {
        // 改造数据
        this.goodsList.forEach(item => {
          item.checked = false
        })
        console.log(this.goodsList);
      },
      computed: {
        totalNum() {
          let num = 0;
          this.goodsList.forEach(item => {
            num += item.num
          });
          return num
        },
        totalPrice() {
          let num = 0;
          this.goodsList.forEach(item => {
            num += item.num * item.price
          });
          return num
        }
      },
      methods: {
        // 勾选全选框
        selectAll() {
          // 全都选中
          this.goodsList.forEach(item => {
              item.checked = this.checkAll
            })
          // if (this.checkAll) {
          //   this.goodsList.forEach(item => {
          //     item.checked = true
          //   })
          // } else {
          //   // 全不
          //   this.goodsList.forEach(item => {
          //     item.checked = false
          //   })
          // }
        },
        // 勾选每一项
        selectItem(index) {
          this.checkAll = this.goodsList.every(item => {
            return item.checked
          })
        }
      }
      
    })
  </script>
</body>

</html>